package com.erp.erp_project.service.impl;

import com.erp.erp_project.core.exception.CustomException;
import com.erp.erp_project.mapper.PowerMapper;
import com.erp.erp_project.mapper.RoleMapper;
import com.erp.erp_project.model.Role;
import com.erp.erp_project.model.User;
import com.erp.erp_project.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author yh
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role,RoleMapper> implements RoleService {



    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PowerMapper powerMapper;

    public RoleServiceImpl(RoleMapper mapper) {
        super(mapper);
    }


    @Override
    public Role query(Integer roleId) {
        return roleMapper.selectById(roleId);
    }

    @Override
    public void updatarole(Role role) throws CustomException {
        Role role1=roleMapper.updateselect(role.getRoleName());
        if(role1!=null&&!role.getRoleId().equals(role1.getRoleId())){
            throw new CustomException("角色名已存在");
        }
        roleMapper.updatarole(role);
    }

    @Override
    public void updatarp(String ids, Integer roleId) {
        roleMapper.updatarp(ids,roleId);
    }

    @Override
    public void add(User user){
        roleMapper.add(user);
    }

    @Override
    public void updataur(User user){
        roleMapper.updataur(user);
    }


    @Override
    public void addrole(String ids,Role role) throws CustomException {
        Role oldrole=roleMapper.updateselect(role.getRoleName());
        if(oldrole!=null){
            throw new CustomException("角色已存在");
        }
        roleMapper.insert(role);
        Role newrole=roleMapper.updateselect(role.getRoleName());
        powerMapper.addrp(newrole.getRoleId(),ids);
    }

    @Override
    public void delete(List ids) throws CustomException {
        for (Object in:ids
             ) {
            Integer uid=roleMapper.selectru(Integer.parseInt((String) in));
            if(uid!=null){
                throw new CustomException("选中的数据中有用户正在使用的角色");
            }
            roleMapper.delete(ids);
            powerMapper.deleterp(ids);
        }
    }

    @Override
    public List<Role> relist(Role role, String rolefield, String condition){
        if(condition!=null&&!condition.trim().equals("")){
            return roleMapper.requeryrole(rolefield,condition);
        }
        int i=1;
        return list(role);
    }
}
